package com.san.common.task;

import java.util.Date;
import java.util.List;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import com.san.common.utils.Constant;
import com.san.oms.domain.ModelScDTO;
import com.san.oms.service.ModelService;
import com.san.oms.service.ScoreService;
import com.san.oms.service.TaskLogService;
import com.san.oms.vo.TaskLogVO;

/**
 * 综合评价计算作业
 * @author Administrator
 *
 */
public class OmsCalcJob implements Job{
	
	@Autowired
	ModelService modelService;
	
	@Autowired
	TaskLogService logService;
	
	@Autowired
	ScoreService service;

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		Date date = new Date();
		String batchNo = date.getTime()+"";
		this.saveLog(batchNo, "模型计算任务开始", null);
		
		List<ModelScDTO> list = modelService.findModelList(null);
		
		for (ModelScDTO modelDTO : list) {
			if (modelDTO.getDelFlag() == Constant.DEL_FLAG_DELETE) {
				continue;
			}
			try {
				service.calc(modelDTO);
			} catch (Exception e) {
				StringBuffer errorMsg = new StringBuffer("模型ID:").append(modelDTO.getModelId()).append("\n");
				errorMsg.append(e.toString()).append("\n");
				StackTraceElement[] ses = e.getStackTrace();
				errorMsg.append(ses[ses.length-1]);
				
				this.saveLog(batchNo, "模型计算任务异常", errorMsg.length() > 4000 ? errorMsg.substring(0, 3999) : errorMsg.toString());
			}
		}
		
		this.saveLog(batchNo, "模型计算任务结束", null);
	}
	
	public void saveLog(String batchNo,String logContent,String errorMsg) {
		TaskLogVO vo = new TaskLogVO();
		vo.setBatchNo(batchNo);
		vo.setLogContent(logContent);
		vo.setErrorMsg(errorMsg);
		
		try {
			logService.save(vo);
		} catch (Exception e1) {
			e1.printStackTrace();
		}
	}
}
